// src/components/NewAgentModal.jsx
import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faXmark } from '@fortawesome/free-solid-svg-icons';

export default function NewAgentModal({ isOpen, onClose, onSubmit }) {
  const default_nodes = {
    '输入型': {
      agent_type: '输入型',
      config: {
        label: '输入节点',
        desc: '设置输入数据',
        inputType: 'string',
        content: '',
        error: null
      }
    },
    '输出型': {
      agent_type: '输出型',
      config: {
        label: '输出节点',
        desc: '展示输出数据',
        out_handle: 'no',
        selectedVariable: '',
        input_data: '',
        content: '',
        error: null,
      }
    },
    '对话型': {
      agent_type: '对话型',
      config: {
        label: '大模型智能体',
        desc: '你是一个有用的AI助手。',
        modelName: 'gpt-3.5-turbo',
        apiUrl: 'https://api.openai.com/v1/chat/completions',
        apiKey: 'xxx',
        maxPrompt: 2000,
        temperature: 0.7,
        content: '',
        error: null
      }
    },
    '工具型': {
      agent_type: '工具型',
      config: {
        label: '工具节点',
        desc: '执行 HTTP 请求 或 python 代码',
        toolName: '',
        execType:'HTTP 请求',
        params: [],
        codeContent: '',
        httpConfig: {url: '', method: 'GET', headers: [{hkey: 'Content-Type', hvalue: 'application/json'}]},
        content: '',
        error: null,
      }
    },
    '网络型': {
      agent_type: '网络型',
      config: {
        label: '网络节点',
        desc: '执行 HTTP 请求，创建成功后可双击配置Header等参数。',
        url: 'https://api.example.com/data',
        method: 'POST',
        headers: [{ key: 'Content-Type', value: 'application/json' }],
        input_data: '',
        content: '',
        error: null,
      }
    }
  };

  const [formData, setFormData] = useState(
    default_nodes['输入型']
  );

  const [defaultData, setDefaultData] = useState(
    default_nodes
  );

  const handleTypeChange = (newType) => {
    setFormData(defaultData[newType]);
  };

  if (!isOpen) return null;

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!formData.config.label) return;
    const cleanConfig = { ...defaultData[formData.agent_type].config };
    Object.keys(cleanConfig).forEach(k => {
      cleanConfig[k] = formData.config[k] || cleanConfig[k];
    });
    
    onSubmit({
      ...formData,
      config: cleanConfig
    });
    onClose();
  };

  const handleConfigChange = (key, value) => {
    setFormData(prev => ({
      ...prev,
      config: {
        ...prev.config,
        [key]: value
      }
    }));

    setDefaultData(prev => ({
      ...prev,
      [formData.agent_type]: {
        ...prev[formData.agent_type],
        config: {
          ...prev[formData.agent_type].config,
          [key]: value
        }
      }
    }));
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[999]">
      <div className="bg-white rounded-lg p-6 w-96 z-[1000]">
        <div className="flex justify-between items-center mb-3">
          <h3 className="text-lg font-semibold">新建智能体</h3>
          <button onClick={onClose} className="text-gray-500 hover:text-gray-700">
            <FontAwesomeIcon icon={faXmark} />
          </button>
        </div>
        
        <form onSubmit={handleSubmit} className="space-y-1">
          <div>
            <label className="block text-sm font-medium mb-1">名称</label>
            <input
              required
              className="w-full px-3 py-2 border rounded-button"
              value={formData.config.label}
              onChange={(e) => handleConfigChange('label', e.target.value)}
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">类型</label>
            <select
              className="w-full px-3 py-2 border rounded-button"
              value={formData.agent_type}
              onChange={(e) => {
                setFormData({...formData, agent_type: e.target.value});
                handleTypeChange(e.target.value);
              }}
            >
              {['输入型', '输出型', '对话型', '工具型', '网络型'].map(type => (
                <option key={type} value={type}>{type}</option>
              ))}
            </select>
          </div>
          <div>
            {formData.agent_type === '对话型' ? (<label className="block text-sm font-medium mb-1">系统提示词</label>) : (<label className="block text-sm font-medium mb-1">描述</label>)}
            <textarea
              required
              className="w-full px-3 py-2 border rounded-button"
              value={formData.config.desc}
              onChange={(e) => { handleConfigChange('desc', e.target.value) } }
            />
          </div>
          

          <div>
          {formData.agent_type === '输入型' && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">输出格式</label>
                <select
                  value={formData.config.inputType}
                  onChange={(e) => handleConfigChange('inputType', e.target.value)}
                  className="w-full px-3 py-2 border rounded-lg"
                >
                  <option value="string">字符串文本</option>
                  <option value="number">数字</option>
                  <option value="boolean">布尔值</option>
                  <option value="json">JSON</option>
                </select>
              </div>
            )}

            {formData.agent_type === '输出型' && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">是否展示输出端点</label>
                <select
                  value={formData.config.out_handle}
                  onChange={(e) => handleConfigChange('out_handle', e.target.value)}
                  className="w-full px-3 py-2 border rounded-lg"
                >
                  <option value="yes">是</option>
                  <option value="no">否</option>
                </select>
              </div>
            )}
            
            {formData.agent_type === '对话型' && (
              <>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">模型名称</label>
                  <input
                    value={formData.config.modelName}
                    onChange={(e) => handleConfigChange('modelName', e.target.value)}
                    className="w-full px-3 py-1 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    API 地址
                  </label>
                  <input
                    value={formData.config.apiUrl}
                    onChange={(e) => handleConfigChange('apiUrl', e.target.value)}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    API Key
                  </label>
                  <input
                    value={formData.config.apiKey}
                    onChange={(e) => handleConfigChange('apiKey', e.target.value)}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div className="grid grid-cols-1 gap-4 mt-2">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      最大 Token 数
                    </label>
                    <input
                      type="number"
                      value={formData.config.maxPrompt || 0}
                      onChange={(e) => handleConfigChange('maxPrompt', e.target.value)}
                      className="w-full px-3 py-2 border rounded-lg"
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    Temperature ({formData.config.temperature || 0})
                  </label>
                  <input
                    type="range"
                    min="0"
                    max="2"
                    step="0.1"
                    value={formData.config.temperature || 0.7}
                    onChange={(e) => handleConfigChange('temperature', e.target.value)}
                    className="w-full"
                  />
                </div>
              </>
            )}

            {formData.agent_type === '工具型' && (
              <div>
                {/* <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">工具名称</label>
                  <input
                    value={formData.config.toolName}
                    onChange={(e) => handleConfigChange('toolName', e.target.value)}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div> */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">执行类型</label>
                  <select
                    value={formData.config.execType}
                    onChange={(e) => handleConfigChange('execType', e.target.value)}
                    className="w-full px-3 py-2 border rounded-lg"
                  >
                    <option value="HTTP 请求">HTTP 请求</option>
                    <option value="Python 代码">Python 代码</option>
                  </select>
                </div>
              </div>
            )}

            {formData.agent_type === '网络型' && (
              <div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">访问地址 URL</label>
                  <input
                    value={formData.config.url}
                    onChange={(e) => handleConfigChange('url', e.target.value)}
                    className="w-full px-3 py-1 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">请求方法</label>
                  <select
                    value={formData.config.method}
                    onChange={(e) => handleConfigChange('method', e.target.value)}
                    className="w-full px-3 py-2 border rounded-lg"
                  >
                    {['GET', 'POST', 'PUT', 'DELETE'].map(method => (
                      <option key={method} value={method}>{method}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    请求数据
                  </label>
                  <textarea
                    value={formData.config.input_data}
                    onChange={(e) => handleConfigChange('input_data', e.target.value)}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
              </div>
            )}

          </div>
          
          <div className="flex justify-end gap-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 border rounded-button"
            >
              取消
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-primary text-white rounded-button"
            >
              创建
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}